import CryptoJS from 'crypto-js'

/**
 * 随机生成32位的字符串
 * @returns {string}
 */
const generateRandomString = () => {
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  const charactersLength = characters.length
  for (let i = 0; i < 32; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

/**
 * 随机生成aes 密钥
 * @returns {string}
 */
export const generateAesKey = () => {
  return CryptoJS.enc.Utf8.parse(generateRandomString())
}

/**
 * 加密base64
 * @returns {string}
 */
export const encryptBase64 = (str: CryptoJS.lib.WordArray) => {
  return CryptoJS.enc.Base64.stringify(str)
}

/**
 * 解密base64
 */
export const decryptBase64 = (str: string) => {
  return CryptoJS.enc.Base64.parse(str)
}

/**
 * 使用密钥对数据进行加密
 * @param message
 * @param aesKey
 * @returns {string}
 */
export const encryptWithAes = (
  message: string,
  aesKey: CryptoJS.lib.WordArray
) => {
  const encrypted = CryptoJS.AES.encrypt(message, aesKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * 使用密钥对数据进行解密
 * @param message
 * @param aesKey
 * @returns {string}
 */
export const decryptWithAes = (
  message: string,
  aesKey: CryptoJS.lib.WordArray
) => {
  const decrypted = CryptoJS.AES.decrypt(message, aesKey, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return decrypted.toString(CryptoJS.enc.Utf8)
}

// 共用方法
// 时间转换成星期几
export const getweek = (val: any) => {
  const dateObj = new Date(val)
  // 获取星期几的索引（0 表示星期日，1 表示星期一，依此类推）
  const dayIndex = dateObj.getDay()
  // 将索引映射为星期几的名称
  const weekdays = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六'
  ]
  return weekdays[dayIndex]
}

// 时间戳转换成时分
export const convertTimes = (ts: any) => {
  const totalSeconds = Math.floor(ts / 1000000) // 转换为秒
  const hours = Math.floor(totalSeconds / 3600) // 计算小时
  const minutes = Math.floor((totalSeconds % 3600) / 60) // 计算分钟
  const seconds = totalSeconds % 60 // 计算剩余秒
  // 补零到两位数
  const paddedHours = String(hours).padStart(2, '0') // 小时补零
  const paddedMinutes = String(minutes).padStart(2, '0') // 分钟补零
  const paddedSeconds = String(seconds).padStart(2, '0') // 秒补零
  // 如果小时为 0，只显示分秒
  if (hours === 0) {
    return `${paddedMinutes}:${paddedSeconds}`
  }
  // 拼接成 HH:mm:ss 格式
  return `${paddedHours}:${paddedMinutes}:${paddedSeconds}`
}

// 将秒数转换为 HH:MM:SS 格式
export const formatTime = (seconds: number): string => {
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.floor(seconds % 60)
  if (h == 0) {
    return [m, s].map((v) => (v < 10 ? '0' + v : v.toString())).join(':')
  } else {
    return [h, m, s].map((v) => (v < 10 ? '0' + v : v.toString())).join(':')
  }
}

// 将毫秒数转换为 HH:MM:SS 格式
export const formatMsTime = (ms: number): string => {
  // 计算各个时间单位
  const seconds = Math.floor((ms / 1000) % 60)
  const minutes = Math.floor((ms / (1000 * 60)) % 60)
  const hours = Math.floor(ms / (1000 * 60 * 60))

  // 格式化为两位数
  const pad = (num: any) => num.toString().padStart(2, '0')

  return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
}

// 数字转中文函数
export const numberToChinese = (num: number): string => {
  const chineseNums = ['一', '二', '三', '四', '五', '六', '日']
  return chineseNums[num]
}

// 数字学期转大写学期
export const numberToTerm = (num: number) => {
  const chineseNums = ['一', '二']
  return chineseNums[num - 1]
}

// 将时分秒转成秒
export const timeToSeconds = (timeStr: any): any => {
  if (!/^\d{1,2}:\d{1,2}:\d{1,2}$/.test(timeStr)) {
    throw new Error('Invalid time format. Expected HH:mm:ss')
  }

  const parts = timeStr.split(':')
  const hours = parseInt(parts[0], 10)
  const minutes = parseInt(parts[1], 10)
  const seconds = parseInt(parts[2], 10)

  return hours * 3600 + minutes * 60 + seconds
}

// 修改系统名称/logo
export function applyTenantConfig(tenantData: any) {
  if (!tenantData) {
    resetSystemToDefault()
    return
  }
  document.title = tenantData.intro || '智慧教学'
  changeFavicon(tenantData.iconUrl)
}

export function resetSystemToDefault() {
  document.title = '智慧教学'
  changeFavicon('/default-favicon.ico')
}

function changeFavicon(iconUrl: string) {
  let favicon: any = document.querySelector('link[rel="icon"]')
  if (!favicon) {
    favicon = document.createElement('link')
    favicon.rel = 'icon'
    document.head.appendChild(favicon)
  }
  favicon.href = iconUrl
}
